import axios from 'axios';
import { log } from '../ipc/log';
import settings from '../config/settings';

const apiClient = axios.create({
  baseURL: settings.apiBaseUrl,
  timeout: 10000,
});

function formatData(data: any) {
  if (!data) return '无';
  try {
    return JSON.stringify(data, null, 2);
  } catch {
    return String(data);
  }
}

function logRequest(config: any) {
  log.debug?.(
    `请求发送:
URL: ${config.url}
方法: ${config.method}
数据: ${formatData(config.data)}
`
  );
}

function logResponse(response: any) {
  log.debug?.(
    `响应成功:
状态码: ${response.status}
数据: ${formatData(response.data)}
`
  );
}

function logResponseError(error: any) {
  if (error.response) {
    log.error?.(
      `响应错误:
状态码: ${error.response.status}
错误数据: ${formatData(error.response.data)}
`
    );
  } else {
    log.error?.(`请求未成功发出或网络错误: ${error.message}\n`);
  }
}

apiClient.interceptors.request.use(
  (config) => {
    logRequest(config);
    return config;
  },
  (error) => {
    log.error?.(`请求错误: ${error.message}\n`);
    return Promise.reject(error);
  }
);

apiClient.interceptors.response.use(
  (response) => {
    logResponse(response);
    return response;
  },
  (error) => {
    logResponseError(error);
    return Promise.reject(error);
  }
);

export default apiClient;
